package com.link.base.base.reception.service;

import com.link.base.base.accnt.dao.mybatis.mapper.AccountMapper;
import com.link.base.base.accnt.dao.mybatis.mapper.AcctAddressMapper;
import com.link.base.base.accnt.model.AccntFollow;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.model.AcctAddress;
import com.link.base.base.accnt.service.AccntFollowService;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.accnt.service.QdAccountWxService;
import com.link.base.base.image.model.Image;
import com.link.base.base.image.service.AppImageService;
import com.link.base.base.reception.model.*;
import com.link.base.base.reception.mybatis.mapper.ReceptionMapper;
import com.link.base.base.staticvalue.dao.mybatis.mapper.StaticvalueMapper;
import com.link.base.base.staticvalue.model.Staticvalue;
import com.link.base.base.user.service.UserService;
import com.link.base.base.workplan.dao.mybatis.mapper.WorkplanMapper;
import com.link.base.base.workplan.model.Workplan;
import com.link.base.base.workplan.service.WorkplanService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.dao.siebel.mapper.BasicMapperSiebel;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.DateUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author unknown
 * @date unknown
 * @comments 接待-导购助手app使用
 */
@Service
public class ReceptionServiceImpl extends BasicServiceImpl<Reception> implements ReceptionService {
    @Resource
    private ReceptionMapper receptionMapper;
    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private WorkplanMapper workplanMapper;
    @Resource
    private AcctAddressMapper acctAddressMapper;
    @Resource
    private AccountService accountService;
    @Resource
    private AppImageService appImageService;
    @Resource
    private StaticvalueMapper staticvalueMapper;
    @Resource
    private AccntFollowService guideAccntFollowService;

    @Resource
    private QdAccountWxService qdAccountWxService;


    @Resource
    private UserService userService;

    @Resource
    private WorkplanService guideWorkplanService;

    @Override
    public BasicMapper<Reception> getBasicMapper() {
        return receptionMapper;
    }

    @Override
    public BasicMapperSiebel<Reception> getSiebelBasicMapper() throws Exception {
        return null;
    }


    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void insert(Reception entity) throws Exception {

        //添加客户信息
        Account account = new Account();
        account.setId(entity.getAccountId());
        account.setGender(entity.getGender());
        account.setAcctName(entity.getAccountName());
        account.setMobilePhone1(entity.getMobilePhone1());
        account.setMobilePhone2(entity.getMobilePhone2());
        account.setQqNum(entity.getQqNum());
        account.setWechatNum(entity.getWechatNum());

        account.setSource(entity.getSources());
        account.setTelephone(entity.getTelephone());
        account.setAcctAddressId(entity.getAcctAddressId());
        account.setSalesmanId(entity.getSalesmanId());
        account.setBirthday(entity.getBirthday());
        account.setEmail(entity.getEmail());
        account.setAcctStage(entity.getAcctStage());
        account.setAcctStatus(entity.getAccountStatus());

        //CRM默认字段,避免在商机对象中出现太多没必要的字段,所以在后台直接添加默认值了,企点的新建不会出现这些值
        CoreUser user = UserUtil.getUser();
        account.setAcctType("ChannelConsumer");
        account.setAcctLevel("A");
        account.setIsOldCustomer("N");
        account.setCountry("中国");

        account.setProvince(entity.getProvince());
        account.setCity(entity.getCity());
        account.setDistrict(entity.getDistrict());
        account.setAddress(entity.getAddress());

        account.setEmpId(user.getId());
        account.setEmp(user.getFirstName());
        account.setPostnId(user.getPostnId());
        account.setOrgId(user.getOrgId());
        account.setPriceListId(user.getPriceListId());

        //account.setWxOwnOpenId(entity.getWxOwnOpenId());
       // account.setWxAccountId(entity.getWxAccountId());
        account.setAcctChannel(entity.getAcctChannel());
       // account.setAcctChannelType(entity.getAcctChannelType());

        Account tempAccount = accountMapper.queryById(account);

        /*if (null == account.getWxAccountId() || StringUtils.isBlank(account.getWxOwnOpenId())) {
            // 微信客户id及微信客户openid中有一个字段为空,则将两个字段都置空,保证其一致性
            account.setWxOwnOpenId(null);
            account.setWxAccountId(null);
        }*/

        //客户已经存在,则修改信息
        if (tempAccount == null) {
            Long accountId = null;
            if (null == entity.getAccountId()) {
                accountId = keyGenerateService.keyGenerate();
                account.setId(accountId);
                entity.setAccountId(accountId);
            } else {
                account.setId(entity.getAccountId());
            }
            //新建对象
            accountService.insert(account);
            //添加地址信息
            List<AcctAddress> addrList = entity.getAddrList();
            if (addrList != null && addrList.size() > 0) {
                for (AcctAddress guideAccntAddr : addrList) {
                    guideAccntAddr.setAcctId(account.getId());
                    acctAddressMapper.insert(guideAccntAddr);
                }
            }
        } else {
            accountService.update(account);
            // 更新地址
            List<AcctAddress> addrList = entity.getAddrList();
            if (addrList != null && addrList.size() > 0) {
                for (AcctAddress guideAccntAddr : addrList) {
                    if ("update".equals(guideAccntAddr.getRow_status())) {
                        acctAddressMapper.update(guideAccntAddr);
                    } else if ("new".equals(guideAccntAddr.getRow_status())) {
                        guideAccntAddr.setAcctId(account.getId());
                        acctAddressMapper.insert(guideAccntAddr);
                    }
                }
            }
        }

        /*if (null != account.getWxAccountId() && !StringUtils.isBlank(account.getWxOwnOpenId())) {
            try {

                QdAccountWx qdAccountWx = new QdAccountWx();
                qdAccountWx.setAccountId(account.getAccountId());
                qdAccountWx.setWxAccountId(String.valueOf(account.getWxAccountId()));
                qdAccountWx.setCorpid(account.getCorpid());

                QdAccountWx temp = qdAccountWxService.queryByAccntIdAndWxAccntId(qdAccountWx);
                LCLogger.info().withMessageKey("insert")
                        .withMessage("根据客户id及微信客户id查询中间表中是否存在数据").flush();
                if (temp == null) {
                    qdAccountWxService.insert(qdAccountWx);
                    //2017/7/19 UpdatedBy LiQun
                    // 将门店客户和微信客户进行关联
                    accountService.accountWxOwnOpenIdUpdate(account);
                    LCLogger.info().withMessageKey("insert")
                            .withMessage("中间表中不存在关联关系,插入记录;更新门店客户wxAccountId和wxOwnOpenId")
                            .flush();
                }
            } catch (Exception e) {
                LCLogger.withException(e);
            }
        } else {
            // 微信客户id及微信客户openid中有一个字段为空,则将两个字段都置空,保证其一致性
            account.setWxOwnOpenId(null);
            account.setWxAccountId(null);
        }*/

        //添加意向品类
        List<PreferenceProd> preferenceProds = entity.getPreferenceProdList();
        if (preferenceProds != null && preferenceProds.size() > 0) {
            Long id = null;
            for (PreferenceProd preferenceProd : preferenceProds) {
                id = keyGenerateService.keyGenerate();
                preferenceProd.setId(id);
                receptionMapper.preferenceProdInsert(preferenceProd);
            }
        }
        //添加时间进度
        List<GuideSchedule> guideSchedules = entity.getGuideScheduleList();
        if (guideSchedules != null && guideSchedules.size() > 0) {
            Long id = null;
            for (GuideSchedule guideSchedule : guideSchedules) {
                id = keyGenerateService.keyGenerate();
                guideSchedule.setId(id);
                receptionMapper.guideScheduleInsert(guideSchedule);
            }
        }
        //添加意向产品
        List<OptyIntendProduct> intendProds = entity.getIntendProdList();
        if (intendProds != null && intendProds.size() > 0) {
            Long id = null;
            for (OptyIntendProduct intendProd : intendProds) {
                id = keyGenerateService.keyGenerate();
                intendProd.setId(id);
                receptionMapper.intendProdInsert(intendProd);
            }
        }

        /*离店原因*/
        List<LeaveStoreReason> leaveStoreReasonList = entity.getLeaveStoreReasonList();
        if (leaveStoreReasonList != null && leaveStoreReasonList.size() > 0) {
            receptionMapper.insertLeaveStoreReasons(entity);
        }

        entity.setTypeCd("NORMAL_OPTY");
        entity.setStage("FIRST_VIEW");
        entity.setSource("OTHER_SOURCE");
        entity.setOptyName(account.getAcctName() + "的商机");
        entity.setOrgId(user.getOrgId());
        entity.setPostnId(user.getPostnId());
        super.insert(entity);

        //获取下客户的最新信息,并写入跟进
        account = accountMapper.queryById(account);
        //新增的客户需要默认记录一条跟进
        guideAccntFollowService.insertFollowWhenInsertAccnt(account, "CRM", "创建商机", entity);
    }

    /**
     * 更新商机
     *
     * @author lizt
     * 2017年3月15日
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void update(Reception entity) throws Exception {

        CoreUser user = UserUtil.getUser();

        //更新商机
        super.update(entity);
        //更新客户
        Account qa = new Account();
        if (null != entity.getAccountId()) {

            qa.setId(entity.getAccountId());
            qa = accountMapper.queryById(qa);
            LCLogger.info().withMessageKey("update")
                    .withMessage("更新客户信息=>查询客户是否存在").flush();
            if (qa != null) {
                qa.setAcctName(entity.getAccountName());
                qa.setGender(entity.getGender());
                qa.setMobilePhone1(entity.getMobilePhone1());
                qa.setMobilePhone2(entity.getMobilePhone2());
                qa.setAcctStatus(entity.getAccountStatus());
                qa.setAddress(entity.getAddress());
                qa.setAgeGroup(entity.getAgeGroup());
                qa.setQqNum(entity.getQqNum());
                qa.setWechatNum(entity.getWechatNum());
                qa.setSource(entity.getSources());
                qa.setBirthday(entity.getBirthday());
                qa.setTelephone(entity.getTelephone());
                qa.setAcctStage(entity.getAcctStage());
                qa.setAcctAddressId(entity.getAcctAddressId());

                // 关联微信客户id
                /*qa.setWxAccountId(entity.getWxAccountId());
                qa.setWxOwnOpenId(entity.getWxOwnOpenId());


                LCLogger.info().withMessageKey("update")
                        .withMessage("更新客户信息=>客户存在,并更新客户相关信息").flush();
                // 当微信客户
                if (null != qa.getWxAccountId() && !StringUtils.isBlank(qa.getWxOwnOpenId())) {
                    LCLogger.info().withMessageKey("update")
                            .withMessage("更新客户信息=>wxAccountId:" + qa.getWxAccountId()
                                    + ",wxOwnOpenId" + qa.getWxOwnOpenId()).flush();
                    try {
                        QdAccountWx qdAccountWx = new QdAccountWx();
                        qdAccountWx.setAccountId(qa.getId());
                        qdAccountWx.setWxAccountId(String.valueOf(qa.getWxAccountId()));
                        qdAccountWx.setCorpid(entity.getCorpid());
                        QdAccountWx temp = qdAccountWxService.queryByAccntIdAndWxAccntId(qdAccountWx);
                        LCLogger.info().withMessageKey("update")
                                .withMessage("更新客户信息=>根据客户id及微信客户id查询中间表中是否存在数据").flush();
                        if (temp == null) {
                            qdAccountWxService.insert(qdAccountWx);
                            LCLogger.info().withMessageKey("update")
                                    .withMessage("更新客户信息=>中间表中不存在关联关系,插入记录").flush();
                            accountService.accountWxOwnOpenIdUpdate(qa);
                            LCLogger.info().withMessageKey("update")
                                    .withMessage("更新客户信息=>更新当前客户上记录上的wxAccountId:" + qa.getWxAccountId()
                                            + "及wxWonOpenId:" + qa.getWxOwnOpenId()).flush();
                        }
                    } catch (Exception e) {
                        LCLogger.withException(e);
                    }
                } else {
                    // 微信客户id及微信客户openid中有一个字段为空,则将两个字段都置空,保证其一致性
                    qa.setWxAccountId(null);
                    qa.setWxOwnOpenId(null);
                }*/

                accountService.update(qa);

                // 创建人id
                Long createdBy = entity.getCreatedBy();
                if (!user.getId().equals(createdBy)) {
                    // 当前登录人与该商机创建人不一致时,增加一条跟进,表示
                    String currentTime = DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
                    user = userService.queryById(user.getId());
                    guideAccntFollowService.insertFollowWhenInsertAccnt(qa, "CRM", user.getFirstName() + "于" + currentTime + "更新商机", entity);
                }

            } else {
                throw new ServiceException("RECEPTION-002");
            }
        }

        //更新意向品类
        List<PreferenceProd> preferenceProds = entity.getPreferenceProdList();
        if (preferenceProds != null && preferenceProds.size() > 0) {
            Long id = null;
            for (PreferenceProd preferenceProd : preferenceProds) {
                if ("Y".equals(preferenceProd.getDeleteFlag())) {
                    receptionMapper.deletePreferenceProdById(preferenceProd);
                } else {
                    id = preferenceProd.getId();
                    if (id == null) {
                        id = keyGenerateService.keyGenerate();
                        preferenceProd.setId(id);
                        receptionMapper.preferenceProdInsert(preferenceProd);
                    } else {
                        receptionMapper.preferenceProdUpdate(preferenceProd);
                    }
                }
            }
        }
        //更新意向产品
        List<OptyIntendProduct> intendProds = entity.getIntendProdList();
        if (intendProds != null && intendProds.size() > 0) {
            Long id = null;
            for (OptyIntendProduct intendProd : intendProds) {
                if ("Y".equals(intendProd.getDeleteFlag())) {
                    receptionMapper.deleteIntendProdById(intendProd);
                } else {
                    id = intendProd.getId();
                    if (id == null) {
                        id = keyGenerateService.keyGenerate();
                        intendProd.setId(id);
                        receptionMapper.intendProdInsert(intendProd);
                    } else {
                        receptionMapper.intendProdUpdate(intendProd);
                    }
                }
            }
        }
        //更新时间进度
        String curStageName;
        if (!StringUtils.isBlank(entity.getCurrentStage())) {
            Staticvalue staticvalue = new Staticvalue();
            staticvalue.setVal(entity.getCurrentStage());
            staticvalue.setType("ACCNT_STAGE");
            staticvalue.setActiveFlag("Y");
            curStageName = staticvalueMapper.queryLovByValAndType(staticvalue).getName();
        } else {
            curStageName = "";
        }

        List<GuideSchedule> guideSchedules = entity.getGuideScheduleList();
        if (guideSchedules != null && guideSchedules.size() > 0) {
            Long id = null;
            Workplan qwp = new Workplan();
            for (GuideSchedule guideSchedule : guideSchedules) {
                id = guideSchedule.getId();
                //设置日期格式
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                String nowDate = df.format(new Date());
                if (id == null) {
                    id = keyGenerateService.keyGenerate();
                    guideSchedule.setId(id);
                    receptionMapper.guideScheduleInsert(guideSchedule);
                    if (!"N".equals(entity.getGenerateTaskFLag())
                            && !StringUtils.isBlank(guideSchedule.getEstimatedTime())
                            && !"CUSTOMER_REGISTRATION".equals(guideSchedule.getStageName())) {
                        qwp.setId(id);
                        qwp.setObjectId(String.valueOf(id));
                        qwp.setEnd_time(guideSchedule.getEstimatedTime());
                        qwp.setType("DAILY_WORK");
                        qwp.setStatus("NO_START");
                        qwp.setPeriodType("DAY");
                        qwp.setDescription(entity.getAccountName() + "，当前阶段：" + curStageName);
                        qwp.setBegin_time(nowDate);
                        workplanMapper.insert(qwp);
                    }
                } else {
                    //插入任务表,首先判断记录是否存在
                    qwp.setId(id);
                    Workplan guideWorkPlan = workplanMapper.queryById(qwp);
                    if (guideWorkPlan == null) {
                        if (!"N".equals(entity.getGenerateTaskFLag()) && !StringUtils.isBlank(guideSchedule.getEstimatedTime())
                                && !"CUSTOMER_REGISTRATION".equals(guideSchedule.getStageName())) {
                            qwp.setId(id);
                            qwp.setObjectId(String.valueOf(id));
                            qwp.setEnd_time(guideSchedule.getEstimatedTime());
                            qwp.setType("BUSINESS_OPPORTUNITY_UP");
                            qwp.setStatus("NO_START");
                            qwp.setPeriodType("DAY");
                            qwp.setBegin_time(nowDate);
                            qwp.setDescription(entity.getAccountName() + "，当前阶段：" + curStageName);
                            workplanMapper.insert(qwp);
                        }
                    } else {
                        if (!StringUtils.isBlank(guideSchedule.getEstimatedTime())) {
                            guideWorkPlan.setEnd_time(guideSchedule.getEstimatedTime());
                            workplanMapper.update(guideWorkPlan);
                        }
                    }
                    receptionMapper.guideScheduleUpdate(guideSchedule);
                }
            }
        }
    }

    /**
     * 通过ID查询商机信息、测量信息及意向产品
     *
     * @author lizt
     * 2017年3月15日
     */
    @Override
    public Reception queryMoreByOptyId(Reception qo) throws Exception {
        if (null == qo.getId()) {
            throw new ServiceException("RECEPTION-003");
        } else {
            MeasureInfo mi = new MeasureInfo();
            PreferenceProd pp = new PreferenceProd();
            GuideSchedule qs = new GuideSchedule();
            mi.setOptyId(qo.getId());
            pp.setOptyId(qo.getId());
            qs.setOptyId(qo.getId());
            OptyIntendProduct op = new OptyIntendProduct();
            op.setOptyId(qo.getId());
            LeaveStoreReason leaveStoreReason = new LeaveStoreReason();
            leaveStoreReason.setHeadId(qo.getId());
            Reception result = new Reception();
            result = receptionMapper.queryById(qo);
            //List<MeasureInfo> list1= receptionMapper.queryByOptyId(mi);
            List<PreferenceProd> list2 = receptionMapper.queryPrefProdByOptyId(pp);
            List<GuideSchedule> list3 = receptionMapper.queryScheduleByOptyId(qs);
            List<OptyIntendProduct> list4 = receptionMapper.queryIntendProdByOptyId(op);
            List<LeaveStoreReason> leaveStoreReasonList = receptionMapper.queryLeaveStoreReasonList(leaveStoreReason);

            result.setPreferenceProdList(list2);
            result.setGuideScheduleList(list3);
            result.setIntendProdList(list4);
            result.setLeaveStoreReasonList(leaveStoreReasonList);
            // 地址列表
            AcctAddress guideAccntAddr = new AcctAddress();
            guideAccntAddr.setAcctId(qo.getAccountId());

            if (null != qo.getAccountId()) {
                List<AcctAddress> addrList = acctAddressMapper.queryAll(guideAccntAddr);
                result.setAddrList(addrList);
            }
            return result;
        }
    }

    /**
     * 商机提交下一步
     *
     * @author lizt
     * 2017年3月15日
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void optyCommit(Reception qo) throws Exception {
        List<GuideSchedule> list = qo.getGuideScheduleList();
        Staticvalue statusType = new Staticvalue();
        statusType.setType("OPTY_STATUS");
        statusType.setActiveFlag("Y");
        List<Staticvalue> statusList = staticvalueMapper.queryByLovType(statusType);
        Collections.sort(statusList, new Comparator<Staticvalue>() {
            @Override
            public int compare(Staticvalue o1, Staticvalue o2) {
                if (Integer.parseInt(o1.getSeq()) > Integer.parseInt(o2.getSeq())) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
        String status = qo.getOptyStatus();
        if (StringUtils.isBlank(status)) {
            throw new ServiceException("RECEPTION-004");
        } else {
            for (int i = 0; i < statusList.size(); i++) {
                if (statusList.get(i).getVal().equals(status)) {
                    if (i != (statusList.size() - 1)) {
                        qo.setOptyStatus(statusList.get(i + 1).getVal());
                    }

                }
            }
        }
        //获取静态值列表并排序
        Staticvalue stageType = new Staticvalue();
        stageType.setType("ACCNT_STAGE");
        stageType.setActiveFlag("Y");
        List<Staticvalue> stageList = staticvalueMapper.queryByLovType(stageType);
        Collections.sort(stageList, new Comparator<Staticvalue>() {
            @Override
            public int compare(Staticvalue o1, Staticvalue o2) {
                if (Integer.parseInt(o1.getSeq()) > Integer.parseInt(o2.getSeq())) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
        System.out.println("排序后：" + stageList);

        GuideSchedule qs = new GuideSchedule();
        qs.setOptyId(qo.getId());
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = df.format(new Date());
        qo.setPreviousActualDate(nowDate);
        Boolean hasFlag = false;
        String stage = qo.getCurrentStage();
        if (StringUtils.isBlank(stage)) {
            throw new ServiceException("RECEPTION-005");
        } else {
            //推进时间阶段，并更新商机所属的时间进度list
            for (int i = 0; i < stageList.size(); i++) {
                if (stageList.get(i).getVal().equals(stage)) {
                    if (i == (stageList.size() - 1)) {
                        qo.setCurrentStage("");
                        qo.setPreviousStage(stageList.get(i).getVal());
                    } else if (i > 0) {
                        qo.setPreviousStage(stageList.get(i).getVal());
                        qo.setCurrentStage(stageList.get(i + 1).getVal());
                        //遍历当前时间进度列表是否包含下一时间阶段的item
                        for (GuideSchedule scheduleItem : list) {
                            if (stageList.get(i + 1).getVal().equals(scheduleItem.getStageName())) {
                                scheduleItem.setPrevioutStageName(stageList.get(i).getVal());
                                hasFlag = true;
                                break;
                            }
                        }
                        if (!hasFlag) {
                            qs.setStageName(stageList.get(i + 1).getVal());
                            qs.setPrevioutStageName(stageList.get(i).getVal());
                            list.add(qs);
                        }
                    }
                }
            }
        }

        //判断当前提交的时间进度list是否有当前阶段
        boolean includeFlag = false;
        if (list.size() > 0) {
            for (GuideSchedule guideSchedule : list) {
                if (guideSchedule.getStageName() != null) {
                    if (guideSchedule.getStageName().equals(stage)) {
                        guideSchedule.setActualTime(nowDate);
                        if (StringUtils.isBlank(guideSchedule.getEstimatedTime())) {
                            guideSchedule.setEstimatedTime(nowDate);
                        }
                        includeFlag = true;
                        break;
                    }
                } else {
                    throw new ServiceException("RECEPTION-006");
                }
            }
            if (!includeFlag) {
                qs.setActualTime(nowDate);
                qs.setEstimatedTime(nowDate);
                qs.setOptyId(qo.getId());
                qs.setStageName(stage);
                list.add(qs);
            }
            qo.setGuideScheduleList(list);
        }

        update(qo);
    }

    /**
     * 通过商机id查询测量信息
     *
     * @author ouyangzhenqiang
     * 2017年3月16日
     */
    @Override
    public List<MeasureInfo> getOptyMeasure(Long parentId) throws Exception {
        MeasureInfo record = new MeasureInfo();
        record.setOptyId(parentId);
        List<MeasureInfo> mList = receptionMapper.queryByOptyId(record);
        for (MeasureInfo item : mList) {
            Image image = new Image();
            image.setModule("Measure");
            image.setParentid(item.getId());
            List<Image> list = appImageService.queryAll(image);
            item.setList(list);
        }
        return mList;
    }

    /**
     * 提交测量信息
     *
     * @author ouyangzhenqiang
     * 2017年3月17日
     */
    @Override
    public void commitOptyMeasure(ListOfMeasure record) throws Exception {
        /*测量信息列表*/
        List<MeasureInfo> list = record.getList();
        for (MeasureInfo item : list) {
            /*操作方式*/
            String op = item.getRow_status();
            if (ROW_STATUS_INSERT.equals(op)) {
                /*新建*/
                receptionMapper.measureInfoInsert(item);
            } else if (ROW_STATUS_DELETE.equals(op)) {
                /*删除*/
                receptionMapper.deleteMeasureInfoById(item);
            } else {
                /*更新*/
                receptionMapper.measureInfoUpdate(item);
            }
        }
    }

    /**
     * 查询一条时间进度记录
     *
     * @author lizt
     * 2017年3月20日
     */
    @Override
    public GuideSchedule queryScheduleById(GuideSchedule qs) throws Exception {
        return receptionMapper.queryScheduleById(qs);
    }

    /**
     * 根据时间进度生成任务
     *
     * @author lizt
     * 2017年8月18日
     */
    @Override
    public GuideSchedule generateTask(GuideSchedule guideSchedule) throws Exception {
        Long id = guideSchedule.getId();
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = df.format(new Date());
        Workplan qwp = new Workplan();
        if (null == id) {
            id = keyGenerateService.keyGenerate();
            guideSchedule.setId(id);
            receptionMapper.guideScheduleInsert(guideSchedule);
            if (StringUtils.isBlank(guideSchedule.getActualTime())
                    && !StringUtils.isBlank(guideSchedule.getEstimatedTime()) && !"CUSTOMER_REGISTRATION".equals(guideSchedule.getStageName())) {
                qwp.setId(id);
                qwp.setObjectId(String.valueOf(id));
                qwp.setEnd_time(guideSchedule.getEstimatedTime());
                qwp.setType("BUSINESS_OPPORTUNITY_UP");
                qwp.setStatus("NO_START");
                qwp.setPeriodType("DAY");
                qwp.setDescription(guideSchedule.getAccountName() + "，当前阶段：" + guideSchedule.getCurStageName());
                qwp.setBegin_time(nowDate);
                workplanMapper.insert(qwp);
            }
        } else {
            //插入任务表,首先判断记录是否存在
            qwp.setId(id);
            Workplan guideWorkPlan = workplanMapper.queryById(qwp);
            if (guideWorkPlan == null) {
                if (StringUtils.isBlank(guideSchedule.getActualTime())
                        && !StringUtils.isBlank(guideSchedule.getEstimatedTime()) && !"CUSTOMER_REGISTRATION".equals(guideSchedule.getStageName())) {
                    qwp.setId(id);
                    qwp.setObjectId(String.valueOf(id));
                    qwp.setEnd_time(guideSchedule.getEstimatedTime());
                    qwp.setType("BUSINESS_OPPORTUNITY_UP");
                    qwp.setStatus("NO_START");
                    qwp.setPeriodType("DAY");
                    qwp.setBegin_time(nowDate);
                    qwp.setDescription(guideSchedule.getAccountName() + "，当前阶段：" + guideSchedule.getCurStageName());
                    workplanMapper.insert(qwp);
                }
            } else {
                throw new ServiceException("RECEPTION-007");
            }
            receptionMapper.guideScheduleUpdate(guideSchedule);
        }

        return receptionMapper.queryScheduleById(guideSchedule);
    }


    /**
     * 查询商机列表同时根据参数判断是否要查出意向产品列表
     *
     * @author lizt
     * 2017年8月23日
     */
    @Override
    public List<Reception> queryByExamplePage(Reception entity) throws Exception {
        List<Reception> list = super.queryByExamplePage(entity);
        String flag = "Y";
        if (flag.equals(entity.getQueryProdsFlag())) {
            OptyIntendProduct op = null;
            LeaveStoreReason leaveStoreReason = null;
            for (Reception item : list) {
                op = new OptyIntendProduct();
                op.setOptyId(item.getId());
                List<OptyIntendProduct> prodlist = receptionMapper.queryIntendProdByOptyId(op);
                item.setIntendProdList(prodlist);
                leaveStoreReason = new LeaveStoreReason();
                leaveStoreReason.setHeadId(item.getId());
                item.setLeaveStoreReasonList(receptionMapper.queryLeaveStoreReasonList(leaveStoreReason));
            }
        }
        return list;
    }

    @Override
    public List<OptyIntendProduct> queryIntendProdByOptyId(OptyIntendProduct record) throws Exception {
        return receptionMapper.queryIntendProdByOptyId(record);
    }

    @Override
    public List<LeaveStoreReason> queryLeaveStoreReasonList(LeaveStoreReason leaveStoreReason) throws Exception {
        return receptionMapper.queryLeaveStoreReasonList(leaveStoreReason);
    }

    @Override
    public List<Reception> queryAll(Reception entity) throws Exception {
        List<Reception> optyList = super.queryAll(entity);
        // 查询离店原因
        Long optyId = null;
        LeaveStoreReason leaveStoreReason = null;
        for (Reception opty : optyList) {
            optyId = opty.getId();
            leaveStoreReason = new LeaveStoreReason();
            leaveStoreReason.setHeadId(optyId);
            opty.setLeaveStoreReasonList(this.queryLeaveStoreReasonList(leaveStoreReason));
        }
        return optyList;
    }

    @Override
    public Map<String, Object> queryFollowUpByOptyId(Reception record) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Long optyId = record.getId();
            /*文字跟进*/
            AccntFollow guideAccntFollow = new AccntFollow();
            guideAccntFollow.setOptyId(optyId);
            guideAccntFollow.setPageFlag(false);
            List<AccntFollow> guideAccntFollowList = guideAccntFollowService.queryByExamplePage(guideAccntFollow);
            /*测量跟进*/
            List<MeasureInfo> measureInfoList = this.getOptyMeasure(optyId);
            /*任务跟进*/
            Workplan guideWorkplan = new Workplan();
            guideWorkplan.setObjectId(String.valueOf(optyId));
            guideAccntFollow.setPageFlag(false);
            List<Workplan> workplanList = guideWorkplanService.queryByExamplePage(guideWorkplan);
            result.put("textFollowUp", guideAccntFollowList);
            result.put("measureInfoList", measureInfoList);
            result.put("workplanList", workplanList);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @Override
    public List<WaitReception> queryWaitForReceptionsPage(WaitReception reception) throws Exception {
        List<WaitReception> list = receptionMapper.queryWaitForReceptionsPage(reception);
        for (WaitReception item : list) {
            WaitReception temp = receptionMapper.queryTopConfidenceAccount(item);
            if (temp != null) {
                item.setTopConfidence(temp.getTopConfidence());
                item.setTopAccountName(temp.getTopAccountName());
            }
        }
        return list;
    }

    @Override
    public int queryWaitReceptionListNum(WaitReception reception) throws Exception {
        return receptionMapper.queryWaitReceptionListNum(reception);
    }

    @Override
    public List<WaitReceptionList> queryReceptionListByHeadId(WaitReceptionList reception) throws Exception {
        return receptionMapper.queryReceptionListByHeadId(reception);
    }

    @Override
    public WaitReception queryReceptionByHeadId(WaitReception waitreception) throws Exception {
        Long receptionId = waitreception.getId();
        if (null == receptionId) {
            throw new ServiceException("RECEPTION-008");
        }
        // 获取待接待头
        WaitReception waitReception = receptionMapper.queryReceptionById(waitreception);
        if (waitReception != null) {
            // 获取待接待列表
            WaitReceptionList waitReceptionListParam = new WaitReceptionList();
            waitReceptionListParam.setReceptionId(receptionId);
            List<WaitReceptionList> waitReceptionList = receptionMapper.queryReceptionListByHeadId(waitReceptionListParam);
            waitReception.setList(waitReceptionList);
            // 获取待接待参考列表下的最新接待记录
            for (WaitReceptionList item: waitReceptionList) {
                Long accountId = item.getAccountId();
                if (null != accountId) {
                    Reception reception = new Reception();
                    reception.setAccountId(accountId);
                    reception = receptionMapper.queryLastReceptionByAccountId(reception);
                    item.setReception(reception);
                }
            }
        } else {
            throw new ServiceException("RECEPTION-009");
        }
        return waitReception;
    }

    @Override
    public WaitReception queryTopConfidenceAccount(WaitReception waitReception) throws Exception {
        return receptionMapper.queryTopConfidenceAccount(waitReception);
    }
}
